# -*- coding: utf-8 -*-

from flask import Blueprint,request,flash,jsonify
from flask_login import current_user, login_required, login_user, logout_user
from ..models import UserModel
from ..extensions import login_manager

acct_api_bp = Blueprint(
    'acct_api',
    __name__,
    url_prefix='/api'
)

@acct_api_bp.route('/login', methods=['POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        if not username or not password:
            flash('Invalid input.')
            return jsonify(**{'code': 403,'message': 'username or password is empty' })

        user = UserModel.query.filter_by(email=username).first()
        # 验证用户名和密码是否一致
        if user and user.validate_password(password):
            login_user(user)  # 登入用户
            flash('Login success.')
            return jsonify(**{'code': 0,'message': 'login success', 'data': user.to_json() })
        else:
            return jsonify(**{'code': 403,'message': 'username or password is error' })
    return jsonify(**{'code': 405,'message': 'method not allowed' })


@login_manager.user_loader
def load_user(user_id):
    user = UserModel.query.get(int(user_id))
    return user


@acct_api_bp.route('/user_info', methods=['GET'])
@login_required
def user_info():
    if current_user.is_authenticated:
        resp = {"code": 0, "message": "success", "data": current_user.to_json()}
    else:
        resp = {"code": 401, "message": "user no login"}
    return jsonify(**resp)


@acct_api_bp.route('/logout', methods=['POST'])
@login_required
def logout():
    logout_user()
    return jsonify(**{'code': 0,'message': 'logout success' })